<?php
namespace app\admin\controller;

use app\model\Admin;
use app\model\AuthGroupAccess;
use app\model\AuthRule;
use app\model\Menu;
use app\util\ReturnCode;
use app\util\Tools;

class Login extends Base{

    protected $admin;
    protected $authGroupAccess;
    protected $authRule;
    protected $menu;

    public function __construct(
        Admin $admin,
        AuthGroupAccess $authGroupAccess,
        AuthRule $authRule,
        Menu $menu
    )
    {
        parent::__construct();
        $this->admin = &$admin;
        $this->authGroupAccess = &$authGroupAccess;
        $this->authRule = &$authRule;
        $this->menu = &$menu;
    }

    /**
     *
     * 登陆
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(){
        $username = $this->request->post('userName');
        $password = $this->request->post('password');
        if (!$username)
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少用户名!');
        if (!$password)
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少密码!');
        else
            $password = Tools::userMd5($password);

        try {
            $admin = $this->admin->where(['username' => $username, 'password' => $password])->find();
        } catch (\Exception $e) {
            $admin = [];
        }

        if(empty($admin))
            return $this->buildFailed(ReturnCode::LOGIN_ERROR,'用户名或密码错误');

        $token = $this->buildToken();
        cache('Login:' . $token, json_encode($admin), config('online_time'));
        cache('Login:' . $admin['id'], $token, config('online_time'));
        $return = [
            'id' => $admin['id'],
            'username'  => $admin['username'],
            'nickname' => $admin['nickname'],
            'token' => $token
        ];
        $return['access'] = [];

        if ($admin['id'] === 1) {
            $access = $this->menu->where(['hide' => 0])->select()->toArray();
            $return['access'] = array_values(array_filter(array_column($access, 'url')));
        } else {
            $groups = $this->authGroupAccess->where(['uid' => $admin['id']])->find();
            if ($groups && $groups->group_id) {
                $access = $this->authRule->where(['group_id'=>$groups->group_id])->select()->toArray();
                $return['access'] = array_values(array_unique(array_column($access, 'url')));
            }else{
                $return['access'] = [];
            }
        }


        return $this->buildSuccess($return, '登录成功');
    }

    public function logout(){
        $token = $this->request->header('token');
        cache('Login:' . $token, null);
        cache('Login:' . $this->admin['id'], null);
        return $this->buildSuccess([], '退出成功', ReturnCode::ACCESS_TOKEN_TIMEOUT);
    }
}
